import React, { useState } from 'react';

const Tracklights = React.memo(({ tracklights, cellSize, gap, updateTracklight, deleteMode, deleteTracklight, editTracklightMode, setTracklights }) => {

    const [editingIndex, setEditingIndex] = useState(null);
    const [inputValue, setInputValue] = useState('');

    const handleToggleDirection = (index) => {
        const updated = [...tracklights];
        updated[index].direction = updated[index].direction === 'left' ? 'right' : 'left';
        setTracklights(updated);
    };

    return (
        <g>
            {/* 点击空白区域新增信号机 */}
            {editTracklightMode && Array.from({ length: 1000 }).map((_, index) => {
                const row = Math.floor(index / 100);
                const col = index % 100;
                const exists = tracklights.some(light => light.row === row && light.col === col);
                if (exists) return null;
                return (
                    <rect
                        key={index}
                        x={col * (cellSize + gap)}
                        y={row * (cellSize + gap)}
                        width={cellSize}
                        height={cellSize}
                        fill="transparent"
                        stroke="transparent"
                        onClick={() => {
                            const newLight = { row, col, direction: 'left', name: 'New Light' };
                            setTracklights([...tracklights, newLight]);
                        }}
                    />
                );
            })}

            {tracklights.map((light, index) => {
                const { row, col, direction, state = "red" } = light;
                const centerX = col * (cellSize + gap) + cellSize / 2;
                const centerY = row * (cellSize + gap) + cellSize / 4; // 稍微高于轨道防止重合

                const radius = 6;

                const colorMap = {
                    green: 'green',
                    yellow: 'yellow',
                    red: 'red',
                };

                const activeColor = colorMap[state] || 'red'; // fallback
                const colors = ['black', 'black', activeColor];

                const baseX = centerX - (3 * radius); // 三个灯共 6r，起点从左边开始
                const baseY = centerY;

                const isEditing = editingIndex === index;


                const handleClick = () => {
                    if (deleteMode) {
                        deleteTracklight(index);
                    } else if (editTracklightMode) {
                        handleToggleDirection(index);
                    } else {
                        setEditingIndex(index);
                        setInputValue(tracklights[index].name);
                    }
                };

                return (
                    <g key={index} style={{ cursor: deleteMode ? 'pointer' : 'default' }}>
                        {/* 可编辑信号机标签 */}
                        {isEditing ? (
                            <foreignObject
                                x={baseX - 40}
                                y={baseY - radius - 24}
                                width={80}
                                height={20}
                            >
                                <input
                                    type="text"
                                    value={inputValue}
                                    onChange={(e) => setInputValue(e.target.value)}
                                    onBlur={() => {
                                        updateTracklight(index, { ...light, name: inputValue });
                                        setEditingIndex(null);
                                    }}
                                    onKeyDown={(e) => {
                                        if (e.key === 'Enter') {
                                            updateTracklight(index, { ...light, name: inputValue });
                                            setEditingIndex(null);
                                        }
                                    }}
                                    style={{ fontSize: '10px', width: '100%' }}
                                    autoFocus
                                />
                            </foreignObject>
                        ) : (
                            <text
                                x={baseX - 2}
                                y={baseY - radius - 6}
                                fontSize="10"
                                fill="#000"
                                textAnchor="start"
                                style={{ cursor: 'pointer' }}
                                onClick={handleClick}
                            >
                                {light.name}
                            </text>
                        )}

                        {/* 三个横向紧贴的信号灯 */}
                        {colors.map((color, i) => (
                            <circle
                                key={i}
                                cx={baseX + i * radius * 2 + radius}
                                cy={baseY}
                                r={radius}
                                fill={color}
                                stroke="#000"
                                onClick={handleClick}
                            />
                        ))}

                        {/* 朝向指示竖线：紧贴红灯右侧 */}
                        {direction === 'left' && (
                            <line
                                x1={baseX + 3 * radius * 2}
                                y1={baseY - radius - 3}
                                x2={baseX + 3 * radius * 2}
                                y2={baseY + radius + 3}
                                stroke="black"
                                strokeWidth={2}
                                onClick={handleClick}
                            />
                        )}

                        {direction === 'right' && (
                            <line
                                x1={baseX}
                                y1={baseY - radius - 3}
                                x2={baseX}
                                y2={baseY + radius + 3}
                                stroke="black"
                                strokeWidth={2}
                                onClick={handleClick}
                            />
                        )}
                    </g>
                );
            })}
        </g>
    );
});

export default Tracklights;